package com.pjb.springbootjjwt.store.storage.myisam;

import com.pjb.springbootjjwt.store.Defines;
import com.pjb.springbootjjwt.store.File;
import com.pjb.springbootjjwt.store.Sql;
import com.pjb.springbootjjwt.store.entity.Error;
import com.pjb.springbootjjwt.store.entity.*;
import com.pjb.springbootjjwt.store.storage.Handler;
import com.pjb.springbootjjwt.store.utils.FileUtil;
import com.pjb.springbootjjwt.store.utils.RandomAccessFileUtil;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * myisam引擎
 */
public class MyisamHandlerImpl implements Handler {

    private static int getMaxNo(String table) throws IOException {
        String c = FileUtil.read(table);
        String[] arr = c.split(";\r\n");
        int count = 0;
        for (String l : arr) {
            if (StringUtils.isEmpty(l)) continue;
            count++;
        }
        return count - 1;
    }

    /**
     * 创建表
     *
     * @param table
     * @param ddl
     * @throws IOException
     */
    public void crateTable(String table, String ddl) throws IOException {
        String path = FileUtil.getPath(table);
        FileUtil.write(path + ".frm", Define.toJson(ddl));
        FileUtil.write(path, "");
    }

    /**
     * 删除表
     *
     * @param table
     * @throws IOException
     */
    public void dropTable(String table) throws Exception {
        FileUtil.removeFile(table);
        FileUtil.removeFile(table + ".frm");
        System.out.println("success.");
    }

    @Override
    public void delete(String table, List<Line> list, List<Line> sub) throws Exception {
        if (sub.isEmpty()) {
            throw new Exception("" + Response.error.set(Error.E90003, table));
        }
        int lineSize = FileUtil.getLineSize(table);

        for (Line line : sub) {
            if (list.contains(line)) {
                int no = Integer.parseInt(line.getKey());
                RandomAccessFileUtil.delete(table, no, lineSize);
                list.remove(line);
            }
        }
    }

    @Override
    public Record get(String table) throws IOException {
        String c = FileUtil.read(table);
        String[] array = c.split(RandomAccessFileUtil.sp);
        List<Line> list = new ArrayList<>();
        if (array.length > 0)
            for (String lineStr : array) {
                if (!lineStr.trim().isEmpty() && lineStr.contains(":"))
                    list.add(Line.toLine(lineStr, Defines.fieldsLength(table)));
            }
        return Record.builder().line(list).build();//new Record(list);
    }

    @Override
    public void saveList(String table, List<Line> list) throws Exception {
        StringBuilder txt = new StringBuilder();
        int no = getMaxNo(table);
        List<Integer> fieldsLength = Defines.fieldsLength(table);
        for (Line line : list) {
            if (getIndex(table, line.getKey())) { //  主键冲突检测
                throw new Exception("" + Response.error.set(Error.E90002, table));
            }

            no++;
            line.setNo(no);
            txt.append(line.toText(fieldsLength)).append(RandomAccessFileUtil.sp);
        }

        RandomAccessFileUtil.append(table, txt.toString());
        System.out.println("random txt:" + txt);
    }

    public boolean getIndex(String table, String key) throws IOException {
        String c = FileUtil.read(table);
        String[] arr = c.split(RandomAccessFileUtil.sp);
        List<Integer> fieldsLength = Defines.fieldsLength(table);

        String ddl = File.getInstance().getDDL(table);
        int pkIndex = Sql.getInstance().getPKIndex(ddl);
        for (String lineStr : arr) {
            if (!StringUtils.isEmpty(lineStr) && lineStr.contains(":")) {
                Line line = Line.toLine(lineStr, fieldsLength);
                String pk = line.getData().get(pkIndex);
                if (pk.equals(key)) return true;
            }
        }
        return false;
    }
}
